from unittest import case

import pytest
from selenium import webdriver

from selenium.webdriver.support.expected_conditions import title_is
from selenium.common.exceptions import WebDriverException
from pymysql import MySQLError
import logging
from Page.Page1_login import Page1_login
from Page.Page2_role_assignMenu import Page2_role_assignMenu
from Page.Page3_pay_add_selecrt_product import Page3_pay_add_selecrt_product
from Page.Page4_operator_add import Page4_operator_add
from Page.Page6_pay_config_add_delete import Page6_pay_config_add
from Page.Email_page import EmailLoginPage
from Common.Api_client import ApiClient
from Common.Data_helper import get_endpoint,read_yaml,read_json,read_csv,read_excel
import time
from Common.conntent_db import DB
import os
# 无头模式导包
from selenium.webdriver.chrome.options import Options


class Testcases():
    @pytest.fixture(autouse=True)
    def setup(self):
        # 无头模式

        # 创建Chrome选项对象
        chrome_options = Options()

        # 启用无头模式
        chrome_options.add_argument("--headless=new")  # 新版Chrome推荐使用
        # 添加其他必要参数（解决Jenkins环境问题）
        chrome_options.add_argument("--disable-gpu")  # 禁用GPU加速
        chrome_options.add_argument("--no-sandbox")  # 禁用沙箱模式
        chrome_options.add_argument("--disable-dev-shm-usage")  # 解决共享内存问题
        chrome_options.add_argument("--window-size=1920,1080")  # 设置窗口大小

        self.driver = webdriver.Chrome(options=chrome_options)

        self.driver.maximize_window()
        self.client=ApiClient()
        self.endpoint=get_endpoint('auth.login')
        self.url=get_endpoint('url')
        self.config=self.client.connent_db()
        self.db=DB(**self.config)
    def teardown(self):
        time.sleep(10)
        self.driver.quit()
    # 用例一 登录，登录成功
    def test_01_login(self):
        po=Page1_login(self.driver)

        po.open_url(str(self.client.set_config_url(self.url)+self.endpoint['path']))

        po.send_username(self.client.set_config(keys=['auth','loginName']))

        po.send_password(self.client.set_config(keys=['auth','roncooPwd']))
        po.click_login_btn()
        time.sleep(2)
    # 参数登录
    current_dir2 = os.path.dirname(__file__)
    file_path2 = os.path.join(current_dir2, '../Data/auth_login.yaml')

    @pytest.mark.parametrize('case', read_yaml(file_path2))
    def test_02_login(self,case):
        print(case['expected'])
        logging.info(case['expected'])
        try:
            po = Page1_login(self.driver)
            po.open_url(str(self.client.set_config_url(self.url)+self.endpoint['path']))
            po.send_username(case['loginName'])
            po.send_password(case['roncooPwd'])
            po.click_login_btn()
        except Exception as e:
            logging.error(f"登录发生错误{str(e)}",exc_info=True)
        if case['expected']!="登录成功":
            # 获取 点击登录后获取到的内容
            logined_text=po.get_clickedlogin_text()
            print(f"点击登录按钮后获取到的内容{logined_text}")
            assert case['expected']==logined_text

    # 用例二 角色分配菜单，分配权限，分配成功

    current_dir3 = os.path.dirname(__file__)
    file_path3 = os.path.join(current_dir3, '../Data/role_assign.json')
    @pytest.mark.parametrize('case', read_json(file_path3))
    def test_03_fen_menu_role(self,case):
        self.test_01_login()
        po=Page2_role_assignMenu(self.driver)
        print(case['expected'])
        logging.info(case['expected'])
        try:
            # 菜单管理
            po.click_ment()
            sql1 = 'select id,name,number,url,target_name from pms_menu where name = %s '
            prams1 = (case['menu_name'],)
            result1 = self.db.db_select(sql1, prams1)
            print(result1)
            if len(result1)>0:
                logging.info("该信息已存在")
                sql2='delete from pms_menu where id = %s'
                prams2=(result1[0][0])
                result2 = self.db.db_delete(sql2, prams2)
                print(result2)
                print("删除成功")
                logging.info(result2)

            # 菜单添加按钮
            po.click_add_menu()
            # 输入菜单名称
            po.send_menu_name(case['menu_name'])
            # 输入菜单编号
            po.send_menu_number(case['menu_number'])
            # 输入菜单uri
            po.send_url(case['menu_url'])
            # 输入菜单navTabId
            po.send_navTabId(case['menu_navTabId'])
            # 点击保存按钮
            po.click_save_menu()
            time.sleep(1)

            # 弹窗返回内容
            men_text = po.get_tean_text()
            print(f"菜单返回内容{men_text}")
            logging.info(f'菜单返回内容{men_text}')
            assert case['expected'] == men_text
            # time.sleep(2)
            # 弹窗确认按钮
            po.click_que()
            time.sleep(5)
            self.db.db_close()
            sql3 = 'select id,name,number,url,target_name from pms_menu where name = %s '
            prams3 = (case['menu_name'],)
            result3 = self.db.db_select(sql3, prams3)
            print(result3)
            logging.info(result3)
            assert case['menu_name'] == result3[0][1]



            time.sleep(2)
            # 权限管理
            po.click_pms()
            # 权限添加按钮
            po.click_pms_add()

            # 判断权限列表中是否存在
            sql4 = 'select id,permission_name,permission,remark from pms_permission where permission_name = %s '
            prams4 = (case['pms_name'],)
            result4 = self.db.db_select(sql4, prams4)
            print(result4)
            logging.info(result4)
            if len(result4)>0:
                logging.info("该信息已存在")
                sql5='delete from pms_permission where id = %s'
                prams5=(result4[0][0])
                result5 = self.db.db_delete(sql5, prams5)
                print(result5)
                print("删除成功")
                logging.info(result5)

            # 权限信息名称
            po.send_pms_name(case['pms_name'])
            # 权限标识
            po.send_pms_permission(case['pms_permission'])
            # 权限描述
            po.send_pms_remark(case['pms_remark'])
            # 权限保存按钮
            po.click_pms_save()
            time.sleep(2)

            # 弹窗返回内容
            pms_text = po.get_tean_text()
            print(f"权限返回内容{pms_text}")
            logging.info(f"权限返回内容{pms_text}")
            assert case['expected'] == pms_text
            po.click_que()
            self.db.db_close()
            sql6='select id,permission_name,permission,remark from pms_permission where permission_name = %s '
            prams6=(case['pms_name'],)
            result6 = self.db.db_select(sql6, prams6)
            print(result6)
            logging.info(result6)
            assert case['pms_name'] == result6[0][1]

            time.sleep(2)
            # 角色管理
            po.click_role()
            # 角色添加按钮
            po.click_role_add()

            sql7='select id,role_name,role_code,remark from pms_role where role_name = %s '
            prams7=(case['role_name'],)
            result7 = self.db.db_select(sql7, prams7)
            print(result7)
            logging.info(result7)
            if len(result7)>0:
                sql8='delete from pms_role where id = %s'
                params8=(result7[0][0])
                result8 = self.db.db_delete(sql8, params8)
                print(result8)
                logging.info(result8)
                print("删除成功")

            # 角色名称
            po.send_role_name(case['role_name'])
            # 角色编码
            po.send_role_code(case['role_code'])
            # 角色描述
            po.send_role_remark(case['role_remark'])
            # 角色保存
            po.click_role_save()
            time.sleep(2)

            # 弹窗返回内容
            role_text = po.get_tean_text()
            print(f"角色返回内容{role_text}")
            logging.info(f"角色返回内容{role_text}")
            assert case['expected'] == role_text

            po.click_que()
            time.sleep(5)
            self.db.db_close()
            sql9='select id,role_name,role_code,remark from pms_role where role_name = %s '
            params9=(case['role_name'],)
            result9 = self.db.db_select(sql9, params9)
            print(result9)
            logging.info(result9)
            assert case['role_name'] == result9[0][1]
            time.sleep(2)

            # 分配菜单
            po.click_fen_meun()
            time.sleep(2)
            # 勾选菜单
            po.click_gou_menu()
            # 分配菜单保存
            po.click_fen_save()
            time.sleep(2)

            # 弹窗返回内容
            fen_menu_text = po.get_tean_text()
            print(f"分配菜单返回内容{fen_menu_text}")
            logging.info(f"分配菜单返回内容{fen_menu_text}")
            assert case['expected'] == fen_menu_text
            po.click_que()
            time.sleep(2)
            # 分配权限

            po.click_fen_pms()
            time.sleep(2)
            # 勾选权限
            po.click_gou_pms()
            # 分配权限保存
            po.click_fen_pms_save()
            time.sleep(2)
            # 弹窗返回内容

            fen_pms_text = po.get_tean_text()
            print(f"分配权限返回内容{fen_pms_text}")
            logging.info(f"分配权限返回内容{fen_pms_text}")
            assert case['expected'] == fen_pms_text
            time.sleep(1)
            po.click_que()
        except MySQLError as e:
            logging.error(f"添加支付配置数据库{str(e)}", exc_info=True)
            raise
        except WebDriverException as e:
            logging.error(f"添加支付配置操作{str(e)}", exc_info=True)
            raise
    # 用例三 添加支付支付产品信息并查询
    current_dir4 = os.path.dirname(__file__)
    file_path4 = os.path.join(current_dir4, '../Data/pay_product.csv')

    @pytest.mark.parametrize('case', read_csv(file_path4))
    def test_04_pay_add_select_product(self,case):
        logging.info(case['expected'])
        self.test_01_login()
        po = Page3_pay_add_selecrt_product(self.driver)
        # 支付管理
        po.click_pay()
        time.sleep(2)
        # 支付产品信息
        try:
            po.click_pay_product()
            sql1="select id,product_code,product_name from rp_pay_product where product_code = %s"
            params1=(case['product_code'],)
            result1 = self.db.db_select(sql1, params1)
            logging.info(result1)
            if len(result1)>0:
                sql2="delete from rp_pay_product where id = %s"
                params2 = (result1[0][0],)
                result2 = self.db.db_delete(sql2, params2)
                logging.info(result2)
                logging.info("删除成功")

            # 添加支付产品按钮
            po.click_product_add()
            # 输入产品编码
            po.send_product_code(case['product_code'])
            # 输入产品名称
            po.send_product_name(case['product_name'])
            # 产品提交
            po.click_product_save()
            time.sleep(2)

            # 弹窗返回内容
            men_text = po.get_tean_text()
            print(f"菜单返回内容{men_text}")
            logging.info(men_text)
            assert case['expected'] == men_text
            self.db.db_close()
            sql3='select id,product_code,product_name from rp_pay_product where product_code = %s'
            params3=(case['product_code'],)
            result3 = self.db.db_select(sql3, params3)
            logging.info(result3)
            assert case['product_name']==result3[0][2]
            # time.sleep(2)
            # 弹窗确认按钮
            po.click_que()
            time.sleep(2)
            # 输入搜索名称
            po.send_find_name(case['product_name'])
            # 点击搜索按钮
            po.click_search_btn()
            time.sleep(2)
            # 获取搜索后的得到的产品名称
            product_name=po.get_searched_product_name()
            print(f"搜索的产品名称{product_name}")
            logging.info(f"搜索的产品名称{product_name}")
            assert case['product_name'] == product_name
        except MySQLError as e:
            logging.error(f"添加支付配置数据库{str(e)}", exc_info=True)
            raise
        except WebDriverException as e:
            logging.error(f"添加支付配置操作{str(e)}", exc_info=True)
            raise
    # 用例四 添加角色，并添加添加操作员，使用角色
    current_dir5 = os.path.dirname(__file__)
    file_path5 = os.path.join(current_dir5, '../Data/operator_add.xlsx')
    @pytest.mark.parametrize('case', read_excel(file_path5,'Sheet1'))
    def test_05_operator_add(self,case):
        self.test_01_login()
        # print(case[0])
        print(case.get('expected'))
        logging.info(case.get('expected'))
        po=Page4_operator_add(self.driver)
        # 角色管理
        po.click_role()
        # 角色添加按钮
        po.click_role_add()
        try:
            sql1="select id,role_name,role_code,remark from pms_role where role_name = %s"
            params1=(case.get('role_name'),)
            result1 = self.db.db_select(sql1, params1)
            logging.info(result1)
            if len(result1)>0:
                sql2="delete from pms_role where id = %s"
                params2 = (result1[0][0],)
                result2 = self.db.db_delete(sql2, params2)
                logging.info(result2)

            # 角色名称
            po.send_role_name(case.get('role_name'))
            # 角色编码
            po.send_role_code(case.get('role _code'))
            # 角色描述
            po.send_role_remark(case.get('remark'))
            # 角色保存
            po.click_role_sava()
            time.sleep(2)

            # 弹窗返回内容
            role_text = po.get_tean_text()
            print(f"角色返回内容{role_text}")
            assert case.get('expected') == role_text
            po.click_que()
            self.db.db_close()
            sql3='select id,role_name,role_code,remark from pms_role where role_name = %s'
            params3=(case.get('role_name'),)
            result3 = self.db.db_select(sql3, params3)
            logging.info(result3)
            assert case.get('role_name')==result3[0][1]
            time.sleep(2)
            # 操作员管理模块
            po.click_operator()
            # 添加操作员按钮
            po.click_operator_add_btn()
            po.alter_max()

            sql4='select id,real_name,login_name,login_pwd,mobile_no,status,remark from pms_operator where real_name = %s'
            params4=(case.get('real_name'),)
            result4 = self.db.db_select(sql4, params4)
            logging.info(result4)
            if len(result4)>0:
                sql5="delete from pms_operator where id = %s"
                params5 = (result4[0][0],)
                result5 = self.db.db_delete(sql5, params5)
                logging.info(result5)

            # 输入操作员姓名
            po.send_realName(case.get('real_name'))
            # 输入操作员登录名
            po.send_loginName(case.get('login_name'))
            # 输入密码
            po.send_loginPwd(case.get('login_pwd'))
            # 输入手机号
            po.send_mobileNo(case.get('mobile_no'))

            # 选择操作员状态
            # po.chose_status('激活')

            time.sleep(5)
            # 输入描述
            po.send_remark(case.get('remark'))
            # 选择角色
            po.click_chose_role()
            # 点击保存按钮
            po.click_opertaor_save()

            time.sleep(2)
            # 弹窗返回内容
            men_text = po.get_tean_text()
            print(f"菜单返回内容{men_text}")
            logging.info(f"菜单返回内容{men_text}")
            assert case.get('expected') == men_text
            # time.sleep(2)
            # 弹窗确认按钮
            po.click_que()
        except MySQLError as e:
            logging.error(f"添加支付配置数据库{str(e)}", exc_info=True)
            raise
        except WebDriverException as e:
            logging.error(f"添加支付配置操作{str(e)}", exc_info=True)
            raise
    # 用例五 添加角色，并添加添加操作员，使用角色  反例， 添加操作员必填为空
    def test_06_operator_add_failure(self):
        self.test_01_login()
        # print(case[0])

        po = Page4_operator_add(self.driver)
        # 角色管理
        po.click_role()
        # 角色添加按钮
        po.click_role_add()
        try:
            sql1 = "select id,role_name,role_code,remark from pms_role where role_name = %s"
            params1 = ("百度张三",)
            result1 = self.db.db_select(sql1, params1)
            logging.info(result1)
            if len(result1) > 0:
                sql2 = "delete from pms_role where id = %s"
                params2 = (result1[0][0],)
                result2 = self.db.db_delete(sql2, params2)
                logging.info(result2)

            # 角色名称
            po.send_role_name("百度张三")
            # 角色编码
            po.send_role_code(126)
            # 角色描述
            po.send_role_remark("百度张三")
            # 角色保存
            po.click_role_sava()
            time.sleep(2)

            # 弹窗返回内容
            role_text = po.get_tean_text()
            print(f"角色返回内容{role_text}")
            assert "操作成功"== role_text
            po.click_que()
            self.db.db_close()
            sql3 = 'select id,role_name,role_code,remark from pms_role where role_name = %s'
            params3 = ("百度张三",)
            result3 = self.db.db_select(sql3, params3)
            logging.info(result3)
            assert "百度张三" == result3[0][1]
            time.sleep(2)
            # 操作员管理模块
            po.click_operator()
            # 添加操作员按钮
            po.click_operator_add_btn()
            po.alter_max()

            sql4 = 'select id,real_name,login_name,login_pwd,mobile_no,status,remark from pms_operator where real_name = %s'
            params4 = ("百度张三")
            result4 = self.db.db_select(sql4, params4)
            logging.info(result4)
            if len(result4) > 0:
                sql5 = "delete from pms_operator where id = %s"
                params5 = (result4[0][0],)
                result5 = self.db.db_delete(sql5, params5)
                logging.info(result5)

            # 输入操作员姓名
            po.send_realName("")
            # 输入操作员登录名
            po.send_loginName("")
            # 输入密码
            po.send_loginPwd("")
            # 输入手机号
            po.send_mobileNo("")

            # 选择状态
            # po.chose_status('激活')

            time.sleep(2)
            # 输入描述
            po.send_remark("")
            # 选择角色
            po.click_chose_role()
            # 点击保存按钮
            po.click_opertaor_save()

            time.sleep(2)
            # 弹窗返回内容
            men_text = po.get_tean_text()
            print(f"菜单返回内容{men_text}")
            assert "操作成功"== men_text
            # time.sleep(2)
            # 弹窗确认按钮
            po.click_que()
        except MySQLError as e:
            logging.error(f"添加支付配置数据库{str(e)}", exc_info=True)
            raise
        except WebDriverException as e:
            logging.error(f"添加支付配置操作{str(e)}", exc_info=True)
            raise
    # 用例六 添加支付配置信息,和删除信息
    def test_07_pay_config_add_delete(self):
        self.test_01_login()
        po = Page6_pay_config_add(self.driver)
        # 支付模块
        po.click_pay()
        # 点击支付配置信息
        po.click_pay_config()
        try:
            sql1='select id,user_name,product_name from rp_user_pay_config where user_name = %s'
            params1=("张三",)
            result1 = self.db.db_select(sql1, params1)
            logging.info(result1)
            if len(result1)>0:
                sql2="delete from rp_user_pay_config where id = %s"
                params2 = (result1[0][0],)
                result2 = self.db.db_delete(sql2, params2)
                logging.info(result2)

            # 点击添加支付配置按钮
            po.click_pay_config_add()
            time.sleep(2)
            # 选择用户信息
            po.click_search1()
            time.sleep(2)
            po.click_xuanze1()
            # 选择产品信息
            time.sleep(2)
            po.click_search2()
            time.sleep(2)
            po.click_xuanze2()
            # 输入风险预存信息
            po.send_riskDay(11)
            # 选择自动结算
            po.click_radio_yes()
            # 输入ip白名单
            po.send_merchantServerIp('百度张三')
            # 点击保存按钮
            po.click_save()

            # 弹窗返回内容
            men_text = po.get_tean_text()
            print(f"菜单返回内容{men_text}")
            assert "操作成功"== men_text
            sql3 = 'select id,user_name,product_name from rp_user_pay_config where user_name = %s'
            params3=("张三",)
            result3 = self.db.db_select(sql3, params3)
            logging.info(result3)
            assert "百度张三"== result3[0][1]
            # time.sleep(2)
            # 弹窗确认按钮
            po.click_que()
            time.sleep(5)

            # isshangjia=po.get_isshangjia_info()
            # if isshangjia =="上架":
            #     po.click_xiajia()
            po.click_delete()
            time.sleep(2)
        except MySQLError as e:
            logging.error(f"添加支付配置数据库{str(e)}", exc_info=True)
            raise
        except WebDriverException as e:
            logging.error(f"添加支付配置操作{str(e)}", exc_info=True)
            raise
    # 邮箱
    def test_08_login(self):
        po=EmailLoginPage(self.driver)
        po.open_url("https://email.163.com/")
        # 进入iframe 框架
        po.join_iframe()
        po.send_username("L19030686321")

        po.send_password("Ljl031030")
        po.click_login_btn()
        # 退出frame框架
        po.default_content()
        time.sleep(2)
